package com.sky.controller.admin;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

import static com.sky.constant.MessageConstant.UPLOAD_FAILED;

@RestController
@RequestMapping("/admin/common")
@Api("文件上传公共接口")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        log.info("开始文件上传");
        //1.获取源文件名
        String originalFilename = file.getOriginalFilename();
        //2.获取源文件名后缀名（截取最后一个点之后字符串）
        String end = originalFilename.substring(originalFilename.lastIndexOf("."));
        //3.UUID加后缀名
        String newName = UUID.randomUUID().toString() + end;
        //4.文件上传，调用上传接口，返回链接
        try {
            String imgUrl = aliOssUtil.upload(file.getBytes(), newName);
            return Result.success(imgUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error(UPLOAD_FAILED);
    }
}
